package com.example.interview.no0106.solution;

import com.example.interview.no0106.Solution;

/**
 * @Description 解答-字符串压缩
 * @ClassName ArraySolution
 * @Author Administrator
 * @Date 2020/7/7 19:36
 * @Version 1.0.0
 */
public class ForSolution implements Solution {
    @Override
    public String compressString(String s) {
        // 字符串为空直接返回
        if(s.length() == 0) {
            return s;
        }

        // 用两个变量记录数据
        char ch = s.charAt(0);
        int times = 0;

        StringBuilder sb = new StringBuilder();
        for(char c : s.toCharArray()) {
            if(c == ch){
                times++;
            } else {
                sb.append(ch).append(times);
                ch = c;
                times = 1;
            }
        }

        //原字符串最后字符会漏掉，这里加上
        sb.append(ch).append(times);

        String res = sb.toString();
        if (res.length() < s.length()) {
            return res;
        } else {
            return s;
        }
    }
}
